<template>
  <div class="hp100">
    <Row class="homer-page flex hp100">
      <!-- {{ homeCompeteImage }}{{ homeLessonImage }}{{ homeDrillImage }} -->
      <Col span="19" class="middle-content-wrap hp100">
        <div class="res-graph-item">
          <!-- competeColorImg2 -->
          <barEchart :src="homeCompeteImage" title="资源统计" echartId="resource" :data="resInfo"
                     :color="homeResChartColor"></barEchart>
        </div>
        <!-- 工程排序 -->
        <div class="graph-wrapper" style="height:50%;">
          <div class="graph-item hp100" >
            <div class="card-item hp100">
              <div class="card-header">本月操作员活跃Top3</div>
              <ul class="card-body" v-if="userEngagement.length > 0">
                <li v-for="item in userEngagement" :key="item.id" class="user-engagement-item">
                  <span class="img"><img :src="item.img" /></span>
                  <Tooltip class="name" :content="item.userName" transfer>
                    <span class="text-ellipsis">{{item.userName}}</span>
                  </Tooltip>
                  <Tooltip class="score" :content="`${item.score}（分）`" transfer>
                    <span class="text-ellipsis">新增积分：{{item.score}}</span>
                  </Tooltip>
                  <Tooltip class="time" :content="formatSeconds(item.duration)" transfer>
                    <span class="text-ellipsis">学习时长：{{formatSeconds(item.duration)}}</span>
                  </Tooltip>
                </li>
              </ul>
              <NoData :loading="loading.userRank" v-else></NoData>
            </div>
          </div>
          <div class="graph-item hp100" >
            <div class="card-item user-rank-card hp100">
              <div class="card-header">操作员排行 <Input class="user-search" placeholder="昵称" v-model="userRank.query.name" @on-change="debounceSearch"></Input></div>
              <div class="card-body" v-if="userRank.total > 0">
                <Table :columns="userRank.column" :data="userRank.data" class="user-rank-table"></Table>
                <Page :total="userRank.total" :curernt="userRank.query.pageIndex"
                      :page-size="userRank.query.pageSize" size="small" class="flex-center mt10" @on-change="changeUserRankPage"></Page>
              </div>
              <NoData :loading="loading.userEngagement" v-else></NoData>
            </div>
          </div>
          <div class="graph-item" v-if="hasCompete">
            <!-- competeColorImg2 -->
            <barEchart :src="homeCompeteImage" title="竞赛模式" echartId="train" :data="competeInfo"
                       :color="homeCompeteChartColor"></barEchart>
          </div>
          <div class="graph-item" v-if="hasTrain">
            <!-- :color="['#AE453D', '#222F42']" -->
            <!-- trainColorImg2 -->
            <barEchart :src="homeLessonImage" title="培训模式" echartId="compete" :data="trainInfo"
                       :color="homeTrainChartColor"></barEchart>
          </div>
          <div class="graph-item" v-if="hasDrill">
            <!-- :color="['#12A3A7', '#222F42']" -->
            <!-- drillColorImg2 -->
            <barEchart :src="homeDrillImage" title="演练模式" echartId="drill" :data="drillInfo"
                       :color="homeDrillChartColor"></barEchart>
            <!-- '#307CED', '#222F42' -->
          </div>
          <div class="graph-item" v-if="hasFz">
            <!-- :color="['#12A3A7', '#222F42']" -->
            <!-- drillColorImg2 -->
            <barEchart :src="homeDrillImage" title="仿真模式" echartId="fz" :data="fzInfo"
                       :color="homeDrillChartColor"></barEchart>
            <!-- '#307CED', '#222F42' -->
          </div>
        </div>
      </Col>
      <Col span="5" class="sider-content-wrap dark-bg hp100 flex-column">
        <!-- 头像信息 -->
        <div class="home-right-baseinfo" v-if="false">
          <div style="
                            display: flex;
                            width: 100%;
                            display: flex;
                            justify-content: flex-end;
                            margin: 20px 0;
                        ">
            <div class="notice-style">
              <Poptip placement="bottom" width="400" style="line-height: initial" id="boardPoptip"
                      v-model="visiblePop">
                            <span style="margin: 0 30px">
                                <Badge :count="notReadCount" style="line-height: initial">
                                    <Icon style="cursor: pointer; color: rgba(255, 255, 255, 0.4)" type="ios-notifications"
                                          :size="24" color="#fff" />
                                </Badge>
                            </span>
                <div class="api" slot="content">
                  <boardlist type="list" @hidePop="hidePop" @showPop="showPop" v-if="showNotice"></boardlist>
                </div>
              </Poptip>
            </div>
            <div class="signout-wrap pointer" v-if="false">
              <Poptip transfer confirm title="确定要退出此用户吗？" placement="left" @on-ok="Signout">
                <img src="../../assets/mainPage/signout.png" style="vertical-align: middle" alt="退出" />
              </Poptip>
            </div>
          </div>
          <div class="avatar-name-wrap">
            <!-- <Avatar icon="ios-person" size="large" :src="setAvater" /> -->
            <img :src="setAvater" style="width: 80px; height: 80px; border-radius: 50%; margin: 0 auto" />
            <p style="
                                color: rgba(255, 255, 255, 0.6);
                                font-size: 16px;
                                font-weight: bold;
                                margin-top: 8px;
                                text-align: center;
                            ">
              {{ nickName }}
            </p>
          </div>
        </div>
        <div class="calendar">
          <div class="calendar-title">
            <div class="value">
              <span class="month">{{ monthValue }}</span>
              <span class="year">{{ calendar.year }}</span>
            </div>
            <ul class="handle clearfix">
              <li @click="setPrevMonth">
                <Icon type="ios-arrow-back" />
              </li>
              <li class="current" @click="setCurrentDate">当前</li>
              <li @click="setNextMonth">
                <Icon type="ios-arrow-forward" />
              </li>
            </ul>
          </div>
          <div class="calendar-content">
            <table>
              <thead>
              <th>日</th>
              <th>一</th>
              <th>二</th>
              <th>三</th>
              <th>四</th>
              <th>五</th>
              <th>六</th>
              </thead>
              <tbody>
              <tr v-for="index in calendarValue.rows" :key="index">
                <td v-for="(item, idx) in calendarValue.data.slice(
                                            (index - 1) * calendar.weekday,
                                            index * calendar.weekday
                                        )" :key="idx">
                  <div class="date" style="cursor: pointer" :class="getCalendarClass(item[0], item[1])"
                       @click="changeCalendarDate(item[0])">
                    {{ item[1].date }}
                  </div>
                </td>
              </tr>
              </tbody>
            </table>
          </div>
        </div>
        <div class="task-list">
          <template v-if="eventList.length > 0">
            <!--  // 0.培训 3.演练 2.竞赛 1.考试 -->
            <div class="task-item flex" v-for="event in eventList" :key="event.id" @click="gotoPage(event)">
              <div class="task-item-icon flex-center" :class="handleType(event.type, 'name')">
                <img :src="handleType(event.type, 'icon')()"
                     style="filter: grayscale(100%) brightness(200%);" />
              </div>
              <div class="task-item-info">
                <span style="display: flex">
                  <p class="task-item-name text-ellipsis">{{ event.name }}</p>
                  <p class="home-task-type">
                    <span class="home-task-type-icon"><i class="el-icon-s-claim"/> </span>
                    
                    {{ handleType(event.type, 'txt') }}</p>
                </span>
                <p class="task-item-time text-ellipsis">
                  {{ event.startTime }} -
                  {{ event.endTime }}
                </p>
              </div>
              <div class="task-item-status" :class="filterStatus(event.status, event.type, 'class')">
                {{ filterStatus(event.status, event.type, 'txt') }}
              </div>
            </div>
          </template>
          <template v-else>
            <NoData></NoData>
          </template>
        </div>
      </Col>
    </Row>
  </div>
</template>
<script>
import encryption from '@/libs/encryption.js';
import cookieUse from '@/libs/cookie.js';
import { debounce,formatSeconds } from '@/libs/utils'
import {
  getDesignCountTran,
  getDrillUserTop,
  getFzUserTop,
  getContestUserTop,
  getTaskDesignList
} from '@/api/homer.js';
import { getSceneInfo, getBatchDeployProgress } from '@/api/drill_compete';
import { getstatusbyprjid } from '@/api/drill';
import { categoryStatistics, userRankStatistics, userEngagementStatistics } from '@/api/homer'
// import { baseInfo, logout } from '@/api/login.js';
import boardlist from '@/view/boardcast/boardcast';
// import ChatRoom from '@/components/chatRoom/chatRoom'
import { mapGetters, mapState, mapActions } from 'vuex';
// 引入组件
import barEchart from './barEchart';
import NoData from '@/components/common/no-data';
import { TimeFormatter, formatDate, showTimeNotSecond } from '@/libs/utils';
import trainColorImg2 from '@/assets/newhome/train-white-blue.png';
import drillColorImg2 from '@/assets/newhome/drill-white-blue.png';
import competeColorImg2 from '@/assets/newhome/compete-white-blue.png';
import trainColorImg from '@/assets/newhome/train-color.png';
import drillColorImg from '@/assets/newhome/drill-color.png';
import competeColorImg from '@/assets/newhome/compete-color.png';
import trainImg from '@/assets/newhome/train.png';
import drillImg from '@/assets/newhome/drill.png';
import competeImg from '@/assets/newhome/compete.png';
import examImg from '@/assets/newhome/drill.png';
export default {
  components: {
    boardlist,
    barEchart,
    NoData
  }, //boards
  data() {
    let today = new Date();
    return {
      formatSeconds,
      today,
      showTimeNotSecond,
      trainColorImg2,
      drillColorImg2,
      competeColorImg2,
      trainColorImg,
      drillColorImg,
      competeColorImg,
      trainImg,
      drillImg,
      competeImg,
      examImg,
      // 个人信息
      USER_ID: '',
      isRootDesinger: false,
      getToken: '',
      setAvater: '',
      nickName: '',
      // 公告
      visiblePop: false,
      showNotice: true,
      trainInfo: {
        total: 0,
        circleData: [],
        barData: [],
        intoPage: 'class'
      },
      competeInfo: {
        total: 0,
        circleData: [],
        barData: [],
        intoPage: 'competitionScene'
      },
      drillInfo: {
        total: 0,
        circleData: [],
        barData: [],
        intoPage: 'drillScene'
      },
      fzInfo:{
        total: 0,
        circleData: [],
        barData: [],
        intoPage: 'fztest'
      },
      resInfo: {
        total: 0,
        barData:[]
      },
      userRank: {
        column: [
          {
            key: 'rank',
            title: '排行',
            width:80
          },
          {
            key: 'nickname',
            title: '昵称',
            tooltip: true
          },
          {
            key: 'totalScore',
            title: '积分',
            tooltip: true
          },
          {
            key: 'duration',
            title: '学习时长',
            tooltip: true
          }
        ],
        data: [],
        total: 0,
        query: {
          pageIndex: 1,
          pageSize: window.outerHeight>1000?5:3,
          name: ''
        }
      },
      userEngagement: [],
      loading:{
        userRank:false,
        userEngagement:false
      },
      // 0培训，1考试，2竞赛，3演练
      type: {
        0: {
          txt: '培训',
          name: 'train',
          // icon: trainImg
          icon: () => {
            return this.homeLessonImage;
          }
        },
        1: {
          txt: '考试',
          name: 'exam',
          // icon: examImg,
          icon: () => {
            return this.designHomeExamImage;
          }
        },
        2: {
          txt: '竞赛',
          name: 'compete',
          // icon: competeImg,
          icon: () => {
            return this.homeCompeteImage;
          }
        },
        3: {
          txt: '演练',
          name: 'drill',
          // icon: drillImg,
          icon: () => {
            return this.homeDrillImage;
          }
        }
      },
      status: {
        train: {
          0: {
            txt: '未开始',
            class: 'wait'
          },
          1: {
            txt: '进行中',
            class: 'process'
          },
          2: {
            txt: '已结束',
            class: 'end'
          }
        },
        compete: {
          0: {
            txt: '准备中',
            class: 'wait'
          },
          2: {
            txt: '进行中',
            class: 'process'
          },
          4: {
            txt: '已结束',
            class: 'end'
          },
          5: {
            txt: '暂停',
            class: 'pause'
          }
        },
        drill: {
          0: {
            txt: '准备中',
            class: 'wait'
          },
          2: {
            txt: '进行中',
            class: 'process'
          },
          4: {
            txt: '已结束',
            class: 'end'
          },
          5: {
            txt: '暂停',
            class: 'pause'
          },
          6:{
            txt:'删除中',
            class: 'end'
          },
          7:{
            txt: '删除失败',
            class: 'end'
          }
        },
        exam: {
          0: {
            txt: '未开始',
            class: 'wait'
          },
          2: {
            txt: '进行中',
            class: 'process'
          },
          1: {
            txt: '已结束',
            class: 'end'
          },
          3: {
            txt: '已结束',
            class: 'end'
          }
        }
      },
      calendar: {
        year: today.getFullYear(),
        month: today.getMonth(), // 显示月-1
        date: today.getDate(),
        weekday: 7,
        state: {},
        check: TimeFormatter.ydm(today.getTime()),
        first: '',
        last: ''
      },
      eventList: [],
      scale:{
        width:'1600px',
        transform:'scale(1)'
      },
      scaleNum:1,
    };
  },
  computed: {
    ...mapGetters(['hasCompete', 'hasDrill', 'hasTrain','hasFz']),
    ...mapState('board', ['notReadCount']), //未读消息数,
    ...mapState('style', {
      homeCompeteImage: ({ themeConfig }) => {
        return themeConfig.homeCompeteImage;
      },
      homeLessonImage: ({ themeConfig }) => {
        return themeConfig.homeLessonImage;
      },
      homeDrillImage: ({ themeConfig }) => {
        return themeConfig.homeDrillImage;
      },
      designHomeExamImage: ({ themeConfig }) => {
        return themeConfig.designHomeExamImage;
      },
      homeCompeteChartColor: ({ themeConfig }) => {
        return [themeConfig.homeCompeteChartColor];
      },
      homeDrillChartColor: ({ themeConfig }) => {
        return [themeConfig.homeDrillChartColor];
      },
      homeTrainChartColor: ({ themeConfig }) => {
        return [themeConfig.homeTrainChartColor];
      },
      homeResChartColor: ({ themeConfig }) => {
        return [themeConfig.homeResChartColor];
      },
      thImage_1: ({ themeConfig }) => {
        return themeConfig.rankFirstImage;
      },
      thImage_2: ({ themeConfig }) => {
        return themeConfig.rankSecondImage;
      },
      thImage_3: ({ themeConfig }) => {
        return themeConfig.rankThirdImage;
      },
      menuMode: ({ themeConfig }) => {
        return themeConfig.menuMode === 'horizontal' ?  'horizontal' : 'vertical';
      },
    }),
    calendarValue() {
      let prev = this.getPrevMonthDate(),
          current = this.getCurrentMonthDate(),
          next = this.getNextMonthDate(),
          data = [...prev, ...current, ...next],
          l = data.length;
      this.calendar.first = data[0][0];
      this.calendar.last = data[l - 1][0];
      return {
        data,
        rows: l / this.calendar.weekday
      };
    },
    monthValue() {
      let vals = [
        // "Jan",
        // "Feb",
        // "Mar",
        // "Apr",
        // "May",
        // "Jun",
        // "Jul",
        // "Aug",
        // "Sept",
        // "Oct",
        // "Nov",
        // "Dec",
        '一月',
        '二月',
        '三月',
        '四月',
        '五月',
        '六月',
        '七月',
        '八月',
        '九月',
        '十月',
        '十一月',
        '十二月'
      ];
      return vals[this.calendar.month];
    }
  },
  beforeDestroy() { },
  watch: {
    $route(to, from) {
      if (to.path == '/bulletin') {
        this.fetchData(to.name);
      }
    }
  },
  mounted() {
    this.scale = this.getScale()
    window.addEventListener('resize',() => {
      this.scale = this.getScale()
    })
    // this.getDesignCountTran();
    // this.getContestUserTop();
    // this.getDrillUserTop();
    // this.getFzUserTop();
    this.renderTrainCalendar();
    this.renderTaskList();
    this.getCategoryStatistics();
    this.getUserEngagementStatistics();
    this.getUserRankStatistics();
  },
  created() {
    // 获取用户id
    setTimeout(() => {
      //如果不使用定时器会低概率出现第一次无法获取到November的问题
      let November = sessionStorage.getItem('November');
      November = JSON.parse(encryption.SelfUseDecrypt(November));
      this.USER_ID = November.userId;
      this.isRootDesinger = November.isRootDesinger;
      this.setAvater = November.avatar;
      this.nickName = November.nickname;
      this.getToken = cookieUse.getCookie('desig-token');
    }, 800);
  },
  methods: {
    getScale(){
      let scale = ((this.menuMode === 'vertical' ? window.innerWidth - 200 : window.innerWidth) / 1600).toFixed(2);
      this.scaleNum = scale;
      if(scale < 1){
        return { width:'1600px',transform:`scale(${scale})`,height:'1620px'}
      }else{
        return {}
      }
    },
    filterStatus(status, type, getType) {
      if ((status === 0 || status) && (type === 0 || type) && (getType === 0 || getType)) {
        return this.status[this.type[type].name][status][getType];
      }
    },
    handleType(type, getType) {
      if ((type === 0 || type) && (getType === 0 || getType)) {
        return this.type[type][getType];
        // 0培训，1考试，2竞赛，3演练
      }
    },
    async getCategoryStatistics() {
      let { data: { code, data } } = await categoryStatistics().catch(error => {
        this.resInfo.barData
      });
      if (code === 1) {
        let { drillCount, onlineUser, caseCount, conCount, targetCount, courseCount, paperCount, expCount,
          totalUser,
          contestCount,
          trainCount,csCount } = data;
        this.resInfo.barData = [
          {
            name: '单位人员',
            value: totalUser,
            unit:'个'
          },
          {
            name: '在线人数',
            value: onlineUser,
            unit:'个'
          },
          {
            name: '理论课件',
            value: data.spExpCount||0,
            unit:'个'
          },
          // {
          //   name: '文本课件',
          //   value: data.wbExpCount||0,
          //   unit:'个'
          // },
          {
            name: '实操课件',
            value: data.scExpCount||0,
            unit:'个'
          },
            
            
          {
            name: '教学',// 原来的培训
            value: trainCount,
            unit:'个'
          },
          {
            name: '专业课程',// 专业课程
            value: courseCount,
            unit:'节'
          },
            
            
            
          // {
          //   name: '复盘',
          //   value: caseCount,
          //   unit:'个'
          // },
          // {
          //   name: '靶标',
          //   value: targetCount,
          //   unit:'个'
          // },

          {
            name: '考核',
            value: data.khCount||0,
            unit:'个'
          },

          {
            name: '试题',
            value: data.paperQuestionCount||0,
            unit:'个'
          },
          {
            name: '试卷',
            value: data.paperCount||0,
            unit:'个'
          },
          // {
          //   name: '竞赛',
          //   value: conCount,
          //   unit:'个'
          // },
          // {
          //   name: '演练',
          //   value: drillCount,
          //   unit:'个'
          // },
          // {
          //   name: '仿真测试',
          //   value: csCount,
          //   unit:'个'
          // },

        ]
      }else{
        this.resInfo.barData = []
      }
    },
    async getUserRankStatistics() {
      this.loading.userRank = true
      this.userRank.query.pageSize = window.outerHeight>1000?5:3
      let { data: { code, data:{items = [],total = 0} } } = await userRankStatistics(this.userRank.query);
      if (code === 1) {
        this.userRank.data = items.map(item => {

          let duration = formatSeconds(item.duration)+''
          let darr = duration.split('分')
          return {
            ...item,
            duration:darr[0]+'分'
          }
        });
        this.userRank.total = total;
      }
      this.loading.userRank = false
    },
    changeUserRankPage(val){
      this.userRank.query.pageIndex = val;
      this.getUserRankStatistics();
    },
    debounceSearch:debounce(function(){
      this.changeUserRankPage(1)
    },500),
    async getUserEngagementStatistics() {
      this.loading.userEngagement = true
      let { data: { code, data=[]} } = await userEngagementStatistics();
      if (code === 1) {
        this.userEngagement = data.map((item,index) => {
          return {
            ...item,
            img: this.rankImage(index+1)
            // img:require(`@/assets/home/top${index+1}.png`)
          }
        })
      }
      this.loading.userEngagement = false
    },
    rankImage (index) {
      let img = ''
      switch (index) {
        case 1:
          img = this.thImage_1
          break;
        case 2:
          img = this.thImage_2
          break;
        case 3:
          img = this.thImage_3
          break;
        default:
          img = ''
          break;
      }
      return img;
    },
    dealData(defaultStatusList, getStatusList, getTrainUserList) {
      let total = getStatusList.reduce((pre, item) => {
        return pre + item.countNum;
      }, 0);
      getStatusList = defaultStatusList.map((item) => {
        let list = data.statusList;
        let info = list.find((a) => a.status === item.status);
        if (info) {
          return {
            status: item.status,
            num: info.countNum,
            per: Number(((info.countNum / total) * 100).toFixed(2))
          };
        } else {
          return item;
        }
      });
      trainList.forEach((item) => {
        item.name = item.userName;
        item.value = item.totalCount;
      });
    },
    getDesignCountTran() {
      getDesignCountTran().then((res) => {
        let { code, data, message } = res.data;
        if (code === 1) {
          let trainList = data.trainUserList;
          let total = data.statusList.reduce((pre, item) => {
            return pre + item.countNum;
          }, 0);
          let statusList = [
            {
              status: 0,
              num: 0,
              per: 0
            },
            {
              status: 1,
              num: 0,
              per: 0
            },
            {
              status: 2,
              num: 0,
              per: 0
            }
          ].map((item) => {
            let list = data.statusList;
            let info = list.find((a) => a.status === item.status);
            if (info) {
              return {
                status: item.status,
                num: info.countNum,
                per: Number(((info.countNum / total) * 100).toFixed(2))
              };
            } else {
              return item;
            }
          });
          trainList.forEach((item) => {
            item.unit = '次';
            item.name = item.userName;
            item.value = item.totalCount;
          });
          Object.assign(this.trainInfo, {
            total,
            circleData: statusList,
            barData: trainList
          });
        } else {
        }
      });
    },
    getContestUserTop() {
      getContestUserTop().then((res) => {
        let { code, data, message } = res.data;
        if (code === 1) {
          let trainList = data.contestUserList;
          let total = data.statusList.reduce((pre, item) => {
            return pre + item.countNum;
          }, 0);
          let statusList = [
            {
              status: 0,
              num: 0,
              per: 0
            },
            {
              status: 2,
              num: 0,
              per: 0
            },
            {
              status: 5,
              num: 0,
              per: 0
            },
            {
              status: 4,
              num: 0,
              per: 0
            }
          ].map((item) => {
            let list = data.statusList;
            let info = list.find((a) => a.status === item.status);
            if (info) {
              return {
                status: item.status,
                num: info.countNum,
                per: Number(((info.countNum / total) * 100).toFixed(2))
              };
            } else {
              return item;
            }
          });
          trainList.forEach((item) => {
            item.unit = '次';
            item.name = item.userName;
            item.value = item.totalCount;
          });
          Object.assign(this.competeInfo, {
            total,
            circleData: statusList,
            barData: trainList
          });
        } else {
        }
      });
    },
    getDrillUserTop() {
      getDrillUserTop().then((res) => {
        let { code, data, message } = res.data;
        if (code === 1) {
          let trainList = data.drillUserList;
          let total = data.statusList.reduce((pre, item) => {
            return pre + item.countNum;
          }, 0);
          let statusList = [
            {
              status: 0,
              num: 0,
              per: 0
            },
            {
              status: 2,
              num: 0,
              per: 0
            },
            {
              status: 5,
              num: 0,
              per: 0
            },
            {
              status: 4,
              num: 0,
              per: 0
            }
          ].map((item) => {
            let list = data.statusList;
            let info = list.find((a) => a.status === item.status);
            if (info) {
              return {
                status: item.status,
                num: info.countNum,
                per: Number(((info.countNum / total) * 100).toFixed(2))
              };
            } else {
              return item;
            }
          });
          trainList.forEach((item) => {
            item.unit = '次';
            item.name = item.userName;
            item.value = item.totalCount;
          });
          Object.assign(this.drillInfo, {
            total,
            circleData: statusList,
            barData: trainList
          });
        } else {
        }
      });
    },
    getFzUserTop() {
      getFzUserTop().then((res) => {
        let { code, data, message } = res.data;
        if (code === 1) {
          let trainList = data.drillUserList;
          let total = data.statusList.reduce((pre, item) => {
            return pre + item.countNum;
          }, 0);
          let statusList = [
            {
              status: 0,
              num: 0,
              per: 0
            },
            {
              status: 2,
              num: 0,
              per: 0
            },
            {
              status: 5,
              num: 0,
              per: 0
            },
            {
              status: 4,
              num: 0,
              per: 0
            }
          ].map((item) => {
            let list = data.statusList;
            let info = list.find((a) => a.status === item.status);
            if (info) {
              return {
                status: item.status,
                num: info.countNum,
                per: Number(((info.countNum / total) * 100).toFixed(2))
              };
            } else {
              return item;
            }
          });
          trainList.forEach((item) => {
            item.unit = '次';
            item.name = item.userName;
            item.value = item.totalCount;
          });
          Object.assign(this.fzInfo, {
            total,
            circleData: statusList,
            barData: trainList
          });
        } else {
        }
      });
    },
    // calendar
    getMonthStart() {
      let d = new Date(this.calendar.year, this.calendar.month);
      return new Date(d.getFullYear(), d.getMonth(), 1);
    },
    getMonthEnd() {
      let d = new Date(this.calendar.year, this.calendar.month);
      return new Date(d.getFullYear(), d.getMonth() + 1, 0);
    },
    getPrevMonthDate() {
      let data = [],
          start = this.getMonthStart(this.calendar.year, this.calendar.month),
          i = start.getDay();
      if (i > 0)
        while (i--)
          data.push(this.format(new Date(this.calendar.year, this.calendar.month, -i)));
      return data;
    },
    getCurrentMonthDate() {
      let data = [],
          end = this.getMonthEnd(this.calendar.year, this.calendar.month),
          i = end.getDate();
      while (i--)
        data.unshift(this.format(new Date(this.calendar.year, this.calendar.month, i + 1)));
      return data;
    },
    getNextMonthDate() {
      let data = [],
          end = this.getMonthEnd(this.calendar.year, this.calendar.month),
          i = this.calendar.weekday - 1 - end.getDay();
      if (i > 0)
        while (i--)
          data.unshift(
              this.format(new Date(this.calendar.year, this.calendar.month + 1, i + 1))
          );
      return data;
    },
    setPrevMonth() {
      this.calendar.month === 0
          ? (this.calendar.year--, (this.calendar.month = 11))
          : this.calendar.month--;
      this.$nextTick(() => {
        this.renderTrainCalendar();
      });
    },
    setNextMonth() {
      this.calendar.month === 11
          ? (this.calendar.year++, (this.calendar.month = 0))
          : this.calendar.month++;
      this.$nextTick(() => {
        this.renderTrainCalendar();
      });
    },
    setCurrentDate() {
      let d = this.format(),
          year = d[1].year,
          month = d[1].month;
      if (
          this.calendar.year !== year ||
          this.calendar.month !== month ||
          this.calendar.check !== d[0]
      ) {
        this.calendar.year = year;
        this.calendar.month = month;
        this.calendar.check = d[0];
        this.$nextTick(() => {
          this.renderTrainCalendar();
        });
      }
    },
    format(d = new Date()) {
      let year = d.getFullYear(),
          month = d.getMonth(),
          date = d.getDate();
      return [
        `${year}-${formatDate(month + 1)}-${formatDate(date)}`,
        {
          year,
          month,
          date
        }
      ];
    },
    getCalendarClass(sDate, oDate) {
      let res = [];
      if (oDate.year === this.calendar.year && oDate.month === this.calendar.month) {
        res.push('current-month-date');
      } else {
        res.push(
            this.calcDate(oDate.year, oDate.month) <
            this.calcDate(this.calendar.year, this.calendar.month)
                ? 'prev-month-date'
                : 'next-month-date'
        );
      }
      this.today.getFullYear() === oDate.year &&
      this.today.getMonth() === oDate.month &&
      this.today.getDate() === oDate.date &&
      res.push("today");
      sDate in this.calendar.state && res.push('value');
      sDate === this.calendar.check && res.push('focus');
      return res;
    },
    calcDate(year, month, date = 1) {
      return new Date(year, month, date).getTime();
    },
    // 培训列表
    renderTrainCalendar() {
      let params = {
        startTime: `${this.calendar.first} 00:00:00`,
        endTime: `${this.calendar.last} 23:59:59`
      };
      getTaskDesignList(params).then((res) => {
        let data = res.data,
            o = {};
        data.data.taskList.forEach((item) => {
          this.getDateList(item.startTime, item.endTime).forEach(
              (item) => (o[item] = !0)
          );
        });
        this.calendar.state = o;
        this.changeCalendarDate(this.calendar.check);
      });
    },
    getDateList(start, end) {
      let sd = start.split(' ')[0],
          te = end.split(' '),
          // ed = end.split(" ")[0],
          ed = te[1] === '00:00:00' ? TimeFormatter.ydm(new Date(end).getTime() - 1) : te[0],
          res = [sd];
      if (sd === ed) return res;
      let st = new Date(sd).getTime(),
          et = new Date(ed).getTime(),
          n = (et - st) / 86400000;
      for (let i = 0; i < n; i++) res.push(TimeFormatter.ydm(st + 86400000 * (i + 1)));
      return res;
    },
    changeCalendarDate(date) {
      // if (date in this.calendar.state) {
      this.calendar.check = date;
      this.renderTaskList();
      // }
    },
    renderTaskList() {
      let params = {
        startTime: `${this.calendar.check} 00:00:01`,
        endTime: `${this.calendar.check} 23:59:59`
      };
      getTaskDesignList(params).then((res) => {
        let data = res.data;
        // 0.培训 3.演练 2.竞赛 1.考试
        this.eventList = data.data.taskList;
      });
    },
    // 图表溢出resize
    overflowResize() {
      const e = document.createEvent('Event');
      e.initEvent('resize', true, true);
      window.dispatchEvent(e);
    },
    // 公告
    hidePop() {
      this.visiblePop = false;
    },
    showPop() {
      this.visiblePop = true;
    },
    gotoPage(item) {
      // 0.培训 3.演练 2.竞赛 1.考试
      switch (item.type) {
        case 0:
          this.gotoTrain(item);
          break;
        case 1:
          this.gotoExam(item);
          break;
        case 2:
        case 3:
          this.gotoScene(item);
          break;
      }
    },
    gotoExam() {
      this.$router.push({
        name: 'exam'
      });
    },
    gotoTrain(item) {
      this.$router.push({
        name: 'courseScheduleDetail',
        params: {
          id: item.id
        }
      });
    },
    getProjectInfo(projectId) {
      return new Promise((resolve, reject) => {
        getstatusbyprjid(projectId).then((data) => {
          if (data.code == 1) {
            resolve(data.attribute.project.status);
          } else if (data.code == -2) {
            resolve('工程不存在');
          } else {
            this.$Message.error(data.message);
          }
        });
      });
    },
    getBatchDeployProgress(projectId) {
      return new Promise((resolve, reject) => {
        getBatchDeployProgress(projectId)
        .then((data) => {
          if (data.code === 1) {
            let quickCreateStatus;
            // 将部署状态替换为分批部署接口返回的实际值
            if (data.data) {
              quickCreateStatus = data.data.status;
            } else {
              quickCreateStatus = 'queryError';
            }
          } else {
            quickCreateStatus = 'queryError';
          }
          resolve(quickCreateStatus);
        })
        .catch((error) => {
          resolve('queryError');
        });
      });
    },
    // 将比赛状态转义,知识赛
    statusEscape(status) {
      switch (status) {
        case 0: // 准备中
        case 1:
          return '0'; // 准备完毕
        case 2: // 开始中
        case 3: // 裁判评判阶段
        case 5:
          return '1'; // 暂停
        case 4:
          return '2'; // 结束
        default:
          return '0';
      }
    },
    gotoScene(item) {
      getSceneInfo(item.id).then(async (data) => {
        let drillDetail = data.data;
        let extension;
        try {
          extension = JSON.parse(drillDetail.extension);
        } catch (e) {
          extension = {};
        }
        let path;
        switch (Number.parseInt(drillDetail.type)) {
          case 0:
            path = '/awdDrillDetail';
            break;
          case 1:
            path = '/awdContestDetail';
            break;
          case 2:
            path = '/ctfContestDetail';
            break;
          case 3:
            path = '/kcContestDetail';
            break;
          case 4:
            path = '/stDrillDetail';
            break;
          case 5:
            if(extension.hwType === 1){
              path = '/swDrillDetail'
            }else{
              if(extension.hwExtentionType === 2) {
                path = '/dailyDrillDetail'
              }else{
                path = '/hwDrillDetail'
              }
            }
            break;
          case 6: // 暂无应急演练页面的跳转
            path = '';
            break;
          case 7:
            path = '/multipleDrillDetail';
            break;
          case 8:
            path = '/awdPlusContestDetail';
            break;
          case 9:
            path = '/opContestDetail';
            break;
          case 10:
            path = '/emergencyDefenseDrillDetail';
        }
        if (Number.parseInt(drillDetail.type) === 3) {
          let query = {
            name: drillDetail.name,
            id: drillDetail.id,
            status: this.statusEscape(drillDetail.progress),
            sTime: drillDetail.startTime,
            eTime: drillDetail.endTime,
            createUserId: drillDetail.creator
          };
          //知识赛
          this.$router.push({
            path: path,
            query: {
              name: drillDetail.name,
              id: drillDetail.id,
            }
          });
          return;
        }
        const deploymentType = extension.deploymentType;
        let deployStatus;
        if (drillDetail.projectId) {
          deployStatus = await this.getProjectInfo(drillDetail.projectId);
          if (deploymentType) {
            quickCreateStatus = await this.getBatchDeployProgress(
                drillDetail.projectId
            );
          }
        }
        if (![2, 4].includes(drillDetail.progress)) {
          // 非结束、进行中的状态，需要看工程状态判断能不能进入场景详情页
          if (
              deployStatus != 3 || // 部署成功允许进入，部署清空后处于未部署状态，也允许进入
              (deploymentType &&
                  ['error', 'deploying', 'queryError'].includes(quickCreateStatus))
          ) {
            //
            this.$Message.warning('未部署成功不可进入！');
            return;
          }
        }
        if (drillDetail.progress == 2) {
          if (
              [0, 1, 2, 9].includes(deployStatus) ||
              (deploymentType && quickCreateStatus === 'deploying')
          ) {
            this.$Message.warning('工程部署中不可进入！');
            return;
          }
        }
        if (drillDetail.projectId) {
          this.$router.push({
            path: path,
            query: {
              id: drillDetail.id, //场景id
              prjid: drillDetail.projectId //环境id
            }
          });
        } else {
          this.$Message.warning('工程不存在！');
        }
      });
    }
  }
};
</script>
<style scoped>
.homer-page {
  transform: scale(1);
  transform-origin: top left;
}

.graph-wrapper {
  display: flex;
  flex-wrap: wrap;
  align-content: space-between;
}

.graph-item {
  padding-right: 20px;
  width: 50%;
  /* height: calc(50% - 10px); */
  height: 400px;
  margin-bottom: 20px;
}

.graph-item:nth-child(even) {
  padding-right: 0px;
}

.graph-item:last-child,
.graph-item:nth-last-of-type(-n + 2):not(:nth-child(even)) {
  margin-bottom: 0px;
}

.card-item {
  display: flex;
  flex-direction: column;
  background: var(--card-body-bgcolor);
  border-radius: 8px 8px 8px 8px;
  padding: 20px 20px 10px;
}

.card-header {
  font-size: 16px;
  font-weight: 700;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
}

.user-engagement-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 55px;
  padding: 0 16px;
  background: transparent;
  /* background: var(--table-th-bgcolor); */
  border-radius: 4px 4px 4px 4px;
  opacity: 1;
  border: 1px solid var(--table-border);
  margin-bottom: 20px;
  color: var(--table-tr-color);
  font-size: 14px;
}

.user-engagement-item .img {
  width: 10%;
}

.user-engagement-item .name,
.user-engagement-item .score,
.user-engagement-item .time {
  width: 30%;
  padding: 0 10px;
}
.user-engagement-item .time{
  width:35%;
}
.user-engagement-item .name {
  font-weight: bold;
}

.user-engagement-item /deep/ .ivu-tooltip-rel,
.user-engagement-item .ivu-tooltip-rel span {
  width: 100%;
}

.res-graph-item {
  width: 100%;
  height: 50%;
  min-height: 300px;
  margin-bottom: 20px;
}
.user-rank-card .user-search {
  width:140px;
}
.user-search /deep/ .ivu-input{
  /* background-color: #F3F3F3; */
  border-radius: 16px;
}
.user-rank-table {
  border: none;
  box-shadow: none;
  border-radius: 0;
}

/deep/.user-rank-table .ivu-table {
  border-radius: 0;
  font-size: 14px;
}

/* /deep/.user-rank-table tbody tr:nth-child(2n) td,
/deep/.user-rank-table tbody tr:nth-child(2n+1) td {
    background-color: #fff !important;
    color: #1D252C !important;
    border-bottom: 1px solid #E7E7E7;
}

/deep/.user-rank-table thead tr th {
    background: #EFF5FE;
    color: #546277;
    font-weight: normal;
    border-bottom: 1px solid #E7E7E7;
} */

/* /deep/.user-rank-card .ivu-page-item-active {
    background: #1563C2;
    border-radius: 2px 2px 2px 2px;
} */

.sider-content-wrap {
  border-radius: 8px;
  overflow: auto;
}

.mt10 {
  margin-top: 10px;
}

/*calendar*/
.calendar {
  height: 368px;
}

.calendar-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 14px;
  height: 80px;
  background: var(--home-cal-head-bgcolor);
}

.calendar-title .value {
  font-size: 24px;
  font-weight: bold;
}

.calendar-title .value .year {
  margin-left: 12px;
  font-size: 14px;
  color: var(--home-cal-year-color);
}

.calendar-title .handle {
  display: flex;
  align-items: center;
}

.calendar-title .handle li {
  height: 16px;
  line-height: 16px;
  cursor: pointer;
}

.calendar-title .handle li i {
  font-weight: bold;
  font-size: 14px;
  color: var(--url-color);
  /*  #3669c3 */
  margin-top: 1px;
  vertical-align: top;
}

.calendar-title .handle li+li {
  margin-left: 18px;
}

.calendar-title .handle li.current {
  font-weight: bold;
  color: var(--url-color);
}

.calendar-content {
  margin-top: 20px;
}

.desig-table-style .calendar-content tbody tr:nth-child(2n) td,
.desig-table-style .calendar-content thead tr th {
  background-color: transparent;
}

.calendar-content table {
  width: 100%;
  height: 280px;
}

.calendar-content table th,
.calendar-content table td {
  text-align: center;
  height: 30px;
}

.calendar-content table th {
  color: var(--home-cal-week-color);
  font-weight: bold;
  cursor: default;
}

.calendar-content table td .date {
  position: relative;
  width: 30px;
  height: 30px;
  line-height: 30px;
  border-radius: 8px;
  margin: auto;
  user-select: none;
}
/* @media (max-width: 1300px) { 
    .calendar-content table td .date{
        width: 2em;
        height: 2em;
        line-height: 2em;
    }
} */
.calendar-content table td .date:before {
  display: none;
  content: '';
  position: absolute;
  left: 0;
  right: 0;
  bottom: 1px;
  z-index: 2;
  width: 5px;
  height: 5px;
  margin: 0 auto;
  border-radius: 50%;
  cursor: pointer;
}

.calendar-content table td .date.current-month-date {
  /* rgba(255, 255, 255, 0.6) */
  color: var(--home-cal-currmonth-day-color);
}

.calendar-content table td .date.prev-month-date,
.calendar-content table td .date.next-month-date {
  color: var(--home-cal-nocurrmonth-day-color);
  /* color: rgba(255, 255, 255, 0.2); */
}

.calendar-content table td .date.focus,
.calendar-content table td .date:hover {
  background-color: var(--home-cal-hastask-day-color);
  /* box-shadow: 0 8px 24px 0 rgba(54, 105, 195, 0.5) !important; */
  color: var(--home-cal-active-day-color);
}

.calendar-content table td .date.value {
  display: block;
  border: 1px solid var(--home-cal-hastask-day-color);
  color: var(--home-cal-hastask-day-color);
}

.calendar-content table td .date.value.today {
  font-weight: bold;
}

.calendar-content table td .date.value.focus,
.calendar-content table td .date.value:hover {
  color: var(--home-cal-active-day-color);
}

.task-list {
  position: relative;
  margin: 20px 15px;
  flex: auto;
  overflow: hidden auto;
  height: 10px;
}

.task-item {
  position: relative;
  padding: 10px;
  background: var(--home-task-bgcolor);
  border-radius: 8px 8px 8px 8px;
  margin-bottom: 10px;
  cursor: pointer;
}

.task-item:hover {
  background: var(--home-task-hover-bgcolor);
}

.task-item-icon {
  flex: none;
  width: 48px;
  height: 48px;
  margin-right: 10px;
  border-radius: 50%;
}

.task-item-info {
  flex: auto;
  width: 0;
}

.task-item-name {
  display: block;
  max-width: 80%;
  color: var(--home-task-title-color);
  font-size: 16px;
}

.task-item-time {
  display: block;
  max-width: 95%;
  color: var(--home-task-time-color);
}

.task-item-status {
  position: absolute;
  right: 0;
  top: 0;
  padding: 2px 6px;
  font-size: 12px;
  border-radius: 0 8px 0 8px;
  color: #fff;
}

.drill {
  /* background: #12a3a7; */
  /* background: var(--home-drill-left-bgcolor);
   */
  background: var(--home-drill-chart-color);
}

.compete {
  /* background: #307ced; */
  background: var(--home-compete-chart-color);
}

.train {
  /* background: #ae453d; */
  background: var(--home-train-chart-color);
}

.exam {
  /* background: #bb8237; */
  background: var(--home-exam-chart-color);
}

.wait {
  background: var(--status-pre);
}

.process {
  background: var(--status-ing);
}

.pause {
  background: var(--status-suspend);
}

.end {
  background: var(--status-deling);
}

/*calendar*/
.dark-bg {
  background-color: var(--card-body-bgcolor) !important;
}

.middle-content-wrap {
  padding: 0 30px 0 0;
  display: flex;
  flex-direction: column;
}

/* 新样式 */
.home-right-baseinfo {
  display: flex;
  flex-direction: column;
  /* justify-content: center; */
  align-items: center;
  position: relative;
  padding: 10px 10px 30px;
}

.avatar-name-wrap {
  display: flex;
  justify-content: center;
  flex-direction: column;
}

/* 公告 */
.notice-style {
  /* position: absolute;
top: 25px;
left: 20px; */
  /* color: #fff; */
  /* cursor: pointer; */
}

.hp100 {
  height: 100%;
}

.flex {
  display: flex;
  align-items: center;
}

.flex-column {
  display: flex;
  flex-direction: column;
}

.flex-center {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
<style>
#boardPoptip .ivu-poptip-body {
  padding: 0px;
}

#app .user-rank-card .ivu-page-item-active a {
  color: #fff !important;
}
.home-task-type{
  opacity: 0.8;
  /*color: var(--home-task-title-color);*/
  line-height: 24px;
  margin-left: 4px;
  border-radius: 4px;
  border: .5px solid rgb(70 141 255);
  background: #f5f6f7;
  transform: scale(0.8);
  padding:0 8px 0 2px;
  white-space: nowrap;
}
.home-task-type-icon{
  height: 18px;
  width: 18px;
  border-radius: 14px;
  display: inline-block;
  color: #2d8cf0;
  text-align: center;
  margin-right: -3px;
}


</style>